import React from 'react';
import { Table,Icon,Popconfirm,Tooltip } from 'antd';
import { DragDropContext, DragSource, DropTarget } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import {observer} from 'mobx-react';
import model from './model';
import Date from '../../utils/date';
import host from '../../conf/hostConf';
import apiConf from '../../conf/apiConf';
const api = apiConf.file;

function dragDirection(
  dragIndex,
  hoverIndex,
  initialClientOffset,
  clientOffset,
  sourceClientOffset,
) {
  const hoverMiddleY = (initialClientOffset.y - sourceClientOffset.y) / 2;
  const hoverClientY = clientOffset.y - sourceClientOffset.y;
  if (dragIndex < hoverIndex && hoverClientY > hoverMiddleY) {
    return 'downward';
  }
  if (dragIndex > hoverIndex && hoverClientY < hoverMiddleY) {
    return 'upward';
  }
}

class RowItems extends React.Component {
  render(){
    return (
      <div className="row-items">{this.props.children}</div>
    );
  }
}

class BodyRow extends React.Component {
  render() {
    const {
      isOver,
      connectDragSource,
      connectDropTarget,
      moveRow,
      dragRow,
      clientOffset,
      sourceClientOffset,
      initialClientOffset,
      ...restProps
    } = this.props;
    const style = { ...restProps.style, cursor: 'move' };

    let className = restProps.className;
    if (isOver && initialClientOffset) {
      const direction = dragDirection(
        dragRow.index,
        restProps.index,
        initialClientOffset,
        clientOffset,
        sourceClientOffset
      );
      if (direction === 'downward') {
        className += ' drop-over-downward';
      }
      if (direction === 'upward') {
        className += ' drop-over-upward';
      }
    }

    return connectDragSource(
      connectDropTarget(
        <tr
          {...restProps}
          className={className}
          style={style}
        />
      )
    );
  }
}

const rowSource = {
  beginDrag(props) {
    return {
      index: props.index,
    };
  },
};

const rowTarget = {
  drop(props, monitor) {
    const dragIndex = monitor.getItem().index;
    const hoverIndex = props.index;
    if (dragIndex === hoverIndex) {
      return;
    }
    props.moveRow(dragIndex, hoverIndex);
    monitor.getItem().index = hoverIndex;
  },
};

const DragableBodyRow = DropTarget('row', rowTarget, (connect, monitor) => ({
  connectDropTarget: connect.dropTarget(),
  isOver: monitor.isOver(),
  sourceClientOffset: monitor.getSourceClientOffset(),
}))(
  DragSource('row', rowSource, (connect, monitor) => ({
    connectDragSource: connect.dragSource(),
    dragRow: monitor.getItem(),
    clientOffset: monitor.getClientOffset(),
    initialClientOffset: monitor.getInitialClientOffset(),
  }))(BodyRow)
);

@observer
class Index extends React.Component {

  components = {
    body: {
      row: DragableBodyRow,
    },
  }
  swapArray= (arr, index1, index2) => {
    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
     return arr;
 }
  moveRow = async (dragIndex, hoverIndex) => {
    if (model.fileList[dragIndex].isFile === model.fileList[hoverIndex].isFile) {
      //相同类型的文件交换顺序
      let origin = model.fileList[dragIndex]['_id'];
      let target = model.fileList[hoverIndex]['_id'];
      let arr = [];
      for (let i = 0;i < model.fileList.length;i++) {
        arr[i] = model.fileList[i];
        if (i === dragIndex) {
          arr[i] = model.fileList[hoverIndex];
        }
        if (i === hoverIndex) {
          arr[i] = model.fileList[dragIndex];
        }
      }
      model.fileList = arr;
      await model.changeIndex(origin,target,dragIndex,hoverIndex);
    }else if (model.fileList[dragIndex].isFile&&!model.fileList[hoverIndex].isFile){
      //如果拖动的是文件，放置的是文件夹，那么就是把该文件移动到文件夹下
    }
    
  }

  render() {
    const columns = [{
      title: (<RowItems>类型</RowItems>),
      dataIndex: 'type',
      key: 'type',
      render: (text, record) => {
        if (text === 'dir') {
          return <Icon type="folder" style={{fontSize:20,color:'#ff0'}} />;
        }else{
          return <Icon type="file-text" style={{fontSize:20,color:'#1890ff'}} />;
        }
      }
    }, {
      title: (<RowItems>文件名称</RowItems>),
      dataIndex: 'filename',
      key: 'filename',
      render: (text,record) => {
        return <RowItems>{text}</RowItems>
      }
    }, {
      title: (<RowItems>文件大小</RowItems>),
      dataIndex: 'size',
      key: 'size',
      render: (text,record) => {
        return <RowItems>{text||'-'}</RowItems>
      }
    }, {
      title: (<RowItems>创建时间</RowItems>),
      dataIndex: 'created_at',
      key: 'created_at',
      render: (text,record) => {
        return <RowItems>{new Date(text).format('yyyy-MM-dd hh:mm:ss')}</RowItems> ;
      }
    }, {
      title: '操作',
      dataIndex:'opt',
      key:'opt',
      render: (text,record) => {
        return (
          <div>
            <Popconfirm title="确定要删除吗？" onConfirm={() => {
              model.deleteFile(record._id);
            }}>
            <Tooltip title="删除">
              <Icon type="delete" style={{cursor:'pointer',marginRight:10,fontSize:20}} />
            </Tooltip>
            </Popconfirm>
            <Tooltip title="下载">
              <Icon type="download" style={{cursor:'pointer',fontSize:20}} onClick={()=>{
                // model.download(record._id);
                window.open(`${host}${api.download}?_id=${record._id}`, 'myIframe');
              }} />
            </Tooltip>
          </div>
          
        );
      }
    }];
    return (
      <div>
        <Table
          columns={columns}
          dataSource={[...model.fileList]}
          components={this.components}
          loading={model.loading}
          onRow={(record, index) => ({
            index,
            moveRow: this.moveRow,
            onDoubleClick:()=>{
              model.openDir(record);
            }
          })}
        />
        <iframe title="myIframe" name="myIframe" style={{display:'none'}}></iframe>
      </div>
      
    );
  }
}

export default DragDropContext(HTML5Backend)(Index);
